<template>
  <div class="channel-edit">
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button size="mini" type="info" @click="editing=!editing">{{editing?'取消':'编辑'}}</van-button>
      </van-cell>
      <van-grid :gutter="8">
        <van-grid-item
        v-for="(item, idx) in channels"
        :key="item.id"
        @click="hClickMyChannel(item)"
        :class="{cur: idx === activeIndex}">
          <span>{{item.name}}</span>
          <van-icon
          name="close"
          class="btn"
          size="0.38rem"
          v-show="editing && idx!==0"
          @click="hDelChannel(item, idx)"></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid :gutter="8">
        <van-grid-item
        v-for="item in recommendChannels"
        :key="item.id"
        @click="hAddChannel(item)">
          <span>{{item.name}}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { getAllChannels, addChannel, delChannel } from '@/api/channel.js'
export default {
  name: 'ChannelEdit',
  props: {
    channels: {
      type: Array,
      required: true
    },
    activeIndex: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      allChannels: [],
      editing: false
    }
  },
  computed: {
    recommendChannels () {
      const result = this.allChannels.filter(channel => {
        const idx = this.channels.findIndex(item => item.id === channel.id)
        return idx === -1
      })
      return result
    }
  },
  created () {
    this.loadAllChannels()
  },
  methods: {
    async hDelChannel (channel, idx) {
      try {
        await delChannel(channel.id)
        this.channels.splice(idx, 1)
        if (idx < this.activeIndex) {
          this.$emit('updateCurIndex', this.activeIndex - 1)
        }
        this.$toast.success('删除成功')
        this.editing = false
      } catch (error) {
        this.$toast.fail('删除失败')
      }
    },
    async hAddChannel (channel) {
      let curChannelList = [...this.channels, channel]
      curChannelList = curChannelList.map((item, idx) => {
        return {
          id: item.id,
          seq: idx
        }
      })
      curChannelList.splice(0, 1)
      console.log(curChannelList)
      await addChannel(curChannelList)
      this.channels.push(channel)
    },
    hClickMyChannel (channel) {
      this.$emit('updateChannel', channel)
    },
    async loadAllChannels () {
      const res = await getAllChannels()
      this.allChannels = res.data.data.channels
    }
  }
};
</script>

<style lang="less" scoped>
.channel {
  padding: 15px;
  font-size: 14px;
}
.btn {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 24px;
}
.cur{
  color: #3196fa;
  font-weight:bold;
}
</style>
